package com.financing.wap.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class SessionUtil {
	
	private static final Session DUMMY = new SessionImpl.EmptySession(); //确保在使用session是不需要判断
	
	/**
	 * 获取用户session
	 * @return
	 */
	public static Session getSession(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Session session = (Session)request.getSession().getAttribute(Session.KEY_NAME);
		if(session == null)
			return DUMMY;
		return session;
	}
	
	/**
	 * 获取用户session
	 * @return
	 */
	public static Session getSession(boolean create){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Session session = (Session)request.getSession().getAttribute(Session.KEY_NAME);
		if(session == null && create){
			session = new SessionImpl();
			getHttpSession().setAttribute(Session.KEY_NAME, session);
		}else if(session == null && !create){
			session = DUMMY;
			getHttpSession().setAttribute(Session.KEY_NAME, session);
		}
		return session;			
	}	
	/**
	 * 设置用户session
	 * @param session
	 */
	public static void setSession(Session session){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		request.getSession(true).setAttribute(Session.KEY_NAME, session);
	}
	
	/**
	 * 获取容器底层session
	 * @return
	 */
	public static HttpSession getHttpSession(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request.getSession(true);
	}
	
	/**
	 * 获取HttpRequest
	 * @return
	 */
	public static HttpServletRequest getHttpRequest(){
		return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
	}
	
}
